﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using MedLink2011.Core;
using MedLink2011.Views.Patients.ChildWindows;
using MedLink2011.Views.Patients.Reports;
using MedLink2011.Web.Models;
using MedLink2011.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using RelayCommand = MedLink2011.Core.RelayCommand;
using System.Windows.Browser;
using MedLink2011.Controls;

namespace MedLink2011.Views.Patients.ViewModels
{
    public class AppointmentViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
    {
        public static MedLink2011Context _appointmentContext;
        private ObservableCollection<Appointment> _appointment;
        private MedLink2011Context _context;
        private EntityQuery<MedLink2011.Web.Models.Patient> _patientQuery;
        private EntityQuery<MedLink2011.Web.Models.Doctor> _doctorQuery;
        //
       public AppointmentViewModel()
        {
            if (!IsDesignTime)
            {
                _appointmentContext = new MedLink2011Context();
                IsBusy = true;
                WireCommands();
                LoadAppointmentAsync();
                LoadComboBoxData();
            }
        }
        
        #region "Load Current Appointment"
        readonly int loadedPatient_Id = MedLink2011.Views.Patients.ViewModels.PatientViewModel.DashLoad_PK;
        //readonly int loadedPatient_Id = 1;
        private void LoadAppointmentAsync()
         {
           if (!_appointmentContext.IsSubmitting)
            {
                if (loadedPatient_Id > 0)
                {
                    PerformAsyncQuery<Appointment>(_appointmentContext, _appointmentContext.GetAppointmentsForPatientsQuery(loadedPatient_Id), AppointmentLoadedComplete);
                }
                else
                {
                    PerformAsyncQuery<Appointment>(_appointmentContext, _appointmentContext.GetAppointmentsQuery(), AppointmentLoadedComplete); 
                }
            }
        }

        private EntitySet<Appointment> _appointmentCollection;
        public EntitySet<Appointment> AppointmentCollection
        {
            get { return _appointmentCollection; }
            set
            {
                _appointmentCollection = value;
                RaisePropertyChanged("AppointmentCollection");
            }
        }

        private Appointment _currentAppointment;
        public Appointment CurrentAppointment
        {
            get { return _currentAppointment; }
            set
            {
                _currentAppointment = value;
                RaisePropertyChanged("CurrentAppointment");
            }
        }

        #endregion "Load Current Appointment"

        #region Commands

        private void EnableCommands()
        {
            AddNewAppointmentCommand.IsEnabled = true;
            SaveAppointmentCommand.IsEnabled = true;
            DeleteAppointmentCommand.IsEnabled = true;
            PrintAppointmentCommand.IsEnabled = true;
            SearchAppointmentCommand.IsEnabled = true;
            SelectionChangedCommand.IsEnabled = true;
            RowLoadedCommand.IsEnabled = true;
            ShowChartDashboardCommand.IsEnabled = true;
           }

        private void WireCommands()
        {
            AddNewAppointmentCommand = new RelayCommand(AddAppointment);
            SaveAppointmentCommand = new RelayCommand(SaveAppointment);
            DeleteAppointmentCommand = new RelayCommand(DeleteAppointment);
            PrintAppointmentCommand = new RelayCommand(PrintAppointment);
            ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
            SearchAppointmentCommand = new RelayCommand<string>(SearchInAppointment);
            SelectionChangedCommand = new RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs>(e =>
            {
                var element = e.OriginalSource as UIElement;
                var element2 = e.OriginalSource as Telerik.Windows.Controls.DataControl;

                if ((element2 != null) && (!_toDelete))
                {
                    var _theItem = element2.SelectedItem;
                    CurrentAppointment = (Appointment) _theItem;
            SelectedPatient =
                PatientCollection.Where(c => c.Patient_Id == CurrentAppointment.Patient_Id).SingleOrDefault();
            SelectedDoctor =
                DoctorCollection.Where(c => c.Doctor_Id == CurrentAppointment.Doctor_Id).SingleOrDefault();
              }
            });
            
            RowLoadedCommand = new RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs>( e =>
                {
                    if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                    {
                        MedLink2011.Web.Models.Appointment model = e.DataElement as MedLink2011.Web.Models.Appointment;
                        var grid = new Grid();
                        var tb = new TextBlock
                               {
                               Text = string.Format(
			"Appointment Date : {0} \r\n"+
			"Comments : {1} \r\n"+
			"Appointment Validity Date : {2} \r\n"+
			"Validity Status : {3} \r\n"+
			"Urgency : {4} \r\n"+
			"Description : {5} \r\n",

			model.Appointment_Date,
			model.Comments,
			model.Appointment_Validity_Date,
			model.Validity_Status,
			model.Urgency,
			model.Description
                     ),
                            Margin = new Thickness(3, 3, 3, 3),
                            Opacity = 0.8,
                            MaxWidth = 250,
                            FontSize = 10,
                            TextWrapping = TextWrapping.NoWrap
                                     };
                        grid.Children.Add(tb);
                        ToolTipService.SetToolTip(e.Row, grid);
                    }
                });
                
           }

        public RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs> RowLoadedCommand
        {
            get;
            private set;
        }

        public RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs> SelectionChangedCommand
        {
            get;
            private set;
        }

        public RelayCommand AddNewAppointmentCommand
        {
            get;
            private set;
        }
        public RelayCommand SaveAppointmentCommand
        {
            get;
            private set;
        }
        public RelayCommand DeleteAppointmentCommand
        {
            get;
            private set;
        }
        public RelayCommand PrintAppointmentCommand
        {
            get;
            private set;
        }

        public RelayCommand<object> ShowChartDashboardCommand
        {
            get;
            private set;
        }

        public RelayCommand<string>  SearchAppointmentCommand
        {
            get;
            private set;
        }

        #endregion Commands
        
        private void SearchInAppointment( string searchText)
        {
            MessageBox.Show(searchText);
        }
        
        private void SaveAppointment()
        {
            CurrentAppointment.Patient_Id = SelectedPatient.Patient_Id;
            CurrentAppointment.Doctor_Id = SelectedDoctor.Doctor_Id;
            CurrentAppointment.write_date = CurrentTime;
            CurrentAppointment.write_uid = CurrentUser;
            _appointmentContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("Appointment se ha actualizado");
                    RaisePropertyChanged("AppointmentCollection");
                    RaisePropertyChanged("CurrentAppointment");
                }
            }, null);
        }
        #region "Add New"
        //http://forums.silverlight.net/forums/p/193377/449256.aspx
        private void AddAppointment()
        {

            MedLink2011.Web.Models.Appointment appointment = new MedLink2011.Web.Models.Appointment();
            AppointmentsAddCW addNewWindow = new AppointmentsAddCW();
            addNewWindow.DataContext = appointment;
            addNewWindow.Closed += (s, ee) =>
            {
                if (addNewWindow.DialogResult == true)
                {
                    appointment.create_date = CurrentTime;
                    appointment.write_date = CurrentTime;
                    appointment.create_uid = CurrentUser;
                    appointment.write_uid = CurrentUser;
                    
                    _appointmentContext.Appointments.Add(appointment);
                    _appointmentContext.SubmitChanges(p =>
                    {
                        if (p.HasError)
                        {
                            p.MarkErrorAsHandled();
                            ErrorWindow.CreateNew(p.Error);
                        }
                        else
                        {
                            MessageBox.Show("New Appointment has been added");
                        }
                    }, null);
                }
            };
            addNewWindow.Show();
            addNewWindow.Closed += FrmClosedAdd;
        }


        void FrmClosedAdd(object sender, EventArgs e)
        {
            LoadAppointmentAsync();
        }
        #endregion "Add New"


        private static int _dashload_PK;
        public static int DashLoad_PK
        {
            get { return _dashload_PK; }
            set { _dashload_PK = value ; }
        }


        private void ShowChartDashboard(object selectedItem)
        {
            //
            string a = selectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            DashLoad_PK = dashLoadPk;
            Uri target = new Uri("/Patients/Pages/PatientsTitlePage?Apointment_id=" + DashLoad_PK, UriKind.Relative);

   
            var _theItem = selectedItem;
            CurrentAppointment = (Appointment)_theItem;
            //NavigationService.Navigate(target);
            //var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
            //if (service != null) service.Navigate(target);
        }



        private static int _current_Patient_id;
        public static int Current_Patient_id
        {
            get { return _current_Patient_id; }
            set { _current_Patient_id = value ; }
        }
        
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
        public string CurrentTime
        {
            get
            {
                DateTime time = DateTime.Now;   
                const string format = "MMM ddd d HH:mm yyyy";  
                return (time.ToString(format));
            }
        }

        public string CurrentUser
        {
            get { return WebContext.Current.User.ToString() ; }
        }


        #region "LoadComboBoxData"

            
        public EntitySet<Patient> PatientCollection { get; set; }
        private Patient _selectedPatient;
        public  Patient SelectedPatient
        {
            get { return _selectedPatient; }
            set
            {
                _selectedPatient = value;
                RaisePropertyChanged("SelectedPatient");
            }
        }
            
        public EntitySet<Doctor> DoctorCollection { get; set; }
        private Doctor _selectedDoctor;
        public  Doctor SelectedDoctor
        {
            get { return _selectedDoctor; }
            set
            {
                _selectedDoctor = value;
                RaisePropertyChanged("SelectedDoctor");
            }
        }
        private long dtStart = 0;
        private long dtEnd = 0;
        void LoadComboBoxData()
        {
            dtStart = System.DateTime.Now.Ticks;
            
            //Patient_IdComboBox
            _context = new MedLink2011Context();
            _patientQuery = _context.GetPatientsQuery();
            _patientQuery = _patientQuery.OrderBy(e => e.Patient_Id);
            PerformAsyncQuery<Patient>(_context, _patientQuery, Patient_IdComboBoxLoaded);
            PatientCollection = _context.Patients;
            
            //Doctor_IdComboBox
            _context = new MedLink2011Context();
            _doctorQuery = _context.GetDoctorsQuery();
            _doctorQuery = _doctorQuery.OrderBy(e => e.Doctor_Id);
            PerformAsyncQuery<Doctor>(_context, _doctorQuery, Doctor_IdComboBoxLoaded);
            DoctorCollection = _context.Doctors;
        }
        
        private void Patient_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Patient> e)
        {
            if (!e.HasError)
            {
                SelectedPatient =
                    PatientCollection.Where(c => c.Patient_Id == CurrentAppointment.Patient_Id).SingleOrDefault();
            }
        }
        private void Doctor_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Doctor> e)
        {
            if (!e.HasError)
            {
                SelectedDoctor =
                    DoctorCollection.Where(c => c.Doctor_Id == CurrentAppointment.Doctor_Id).SingleOrDefault();
            }
        }


        private void AppointmentLoadedComplete(object sender, MedLink2011.Core.EntityResultsArgs<Appointment> e)
        {
            IsBusy = false;
            if (!e.HasError)
            {
                AppointmentCollection = _appointmentContext.Appointments;
                CurrentAppointment = AppointmentCollection.FirstOrDefault();
                EnableCommands();
            SelectedPatient = PatientCollection.Where(c => c.Patient_Id == CurrentAppointment.Patient_Id).SingleOrDefault();
            SelectedDoctor = DoctorCollection.Where(c => c.Doctor_Id == CurrentAppointment.Doctor_Id).SingleOrDefault();

            }
            else
            {
                // notify user if there is any error
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void AddNewForm_Closed(object sender, MedLink2011.Core.EntityResultsArgs<Appointment> e)
        {
            if (!e.HasError)
            {
                
            }
        }


        #endregion "LoadComboBoxData"

        #region "Delete"

        private bool _toDelete=false;

        private void DeleteAppointment()
        {
            _toDelete = true;
            var appointmentToDelete = CurrentAppointment;
           if (appointmentToDelete != null)
                    {
                     var result = MessageBox.Show("Are you sure you wish to delete the Current Appointment?", "Confirm Delete", MessageBoxButton.OKCancel);
                      if (result.Equals(MessageBoxResult.OK))
                        {
            _appointmentContext.Appointments.Remove(appointmentToDelete);
            _appointmentContext.SubmitChanges(o =>
            {
                if (o.HasError)
                {
                    MessageBox.Show("Esta appointment no se puede eliminar ya que existen datos que dependen de esta Appointment.....", "Cancelado", MessageBoxButton.OKCancel);
                    o.MarkErrorAsHandled();
                    _appointmentContext.RejectChanges();
                }
                else
                {
                    MessageBox.Show("el registro de  appointment ha sido eliminado exitosamente ... ");
                    //LoadAppointmentAsync();
                    RaisePropertyChanged("AppointmentCollection");
                    CurrentAppointment = AppointmentCollection.FirstOrDefault();
                }
            }, null);
            }
       }
            _toDelete = false;
        }
        #endregion "Delete"
        
        #region "Print"
        
        private void PrintAppointment()
        {
            if (CurrentAppointment != null)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
                document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
                string PrintQueue = "Appointments_" + CurrentAppointment.ToString(); // to show in the print queue
                document.Print(PrintQueue); //fires when printing has begun
            }
        }
        
        static void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
            }
            else
                MessageBox.Show("Print Complete");
        }
        
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            MedLink2011.Web.Models.Appointment appt = CurrentAppointment as MedLink2011.Web.Models.Appointment;
            if (appt != null)
            {
                //e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
                //if (document.PrintedPageCount > 0)
                //{
                // e.PageVisual = new ChildEntityFReport() { DataContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
                //}
                //else
                e.PageVisual = new AppointmentsFReport() { DataContext = appt };
            }
        }
       
        #endregion "Print"

    }


}

